home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: swap high and low 16 bits?
- Date: Tue, 16 Jan 96 17:06:29 GMT
- Organization: none
- Message-ID: <821811989snz@genesis.demon.co.uk>
- References: <Pine.OSF.3.91.960115174921.19742A-100000@io.UWinnipeg.ca>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <Pine.OSF.3.91.960115174921.19742A-100000@io.UWinnipeg.ca>
- wsimpson@uwinnipeg.ca "Bill Simpson" writes:
-
- >I wanted to obtain a "random" starting number each time a program
- >is run. The obvious choice is time(NULL). The problem with it is that
- >if the program runs and terminates fairly quickly, the number returned by
- >time(NULL) is quite similar each run, differing only by the lowest bits.
- >
- >One solution would be to swap the high 16 bits and the low 16 bits of the
- >32 bit unsigned long int. Sorry this is dirty, not ANSI.
-
- OK, I assume then you have something like :
-
- #include <time.h>
-
- unsigned long val;
-
- val = time(NULL);
-
- That's not strictly portable (for instance time_t could have type double
- and the conversion to unsigned long could trap) but works on many
- implementations.
-
- One simple approach would be to call your random funciton (rand() or whatever)
- a few times and discard the values. The 2 random number sequences should
- diverge quickly for a reasonable RNG algorithm. Another approach might be
-
- ...
- val *= N;
-
- where N is a large odd number. Unsigned arithmetic is modulo arithmetic - it
- can't overflow. Alternatively you could do something like:
-
- val ^= val << 16;
-
- which will cause variation in higher order bits for small changes of val.
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-